package com.soul.recommend.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.soul.model.mongo.Movement;
import com.soul.model.mongo.MovementScore;
import com.soul.model.mongo.Video;
import com.soul.model.mongo.VideoScore;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author mdoya
 * @version 1.0
 * @description: 视频推荐-打分业务实现（为了大数据推荐系统提供基础数据）  生产者是
 */
@Slf4j
@Component
public class RecommendVideoListener {

    @Autowired
    private MongoTemplate mongoTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "soul.video.queue",durable = "true"),
            exchange = @Exchange(value = "soul.log.exchange",type = ExchangeTypes.TOPIC),
            key = {"log.video"} // 绑定key
    ))
    public void listenerMessage(String message){
        log.debug("开始视频推荐打分业务listener监听");
        // 1. 解析字符串
        Map<String,String> map = JSON.parseObject(message, Map.class);
        String userId = map.get("userId");
        String type = map.get("type");
        String logTime = map.get("logTime");
        String busId = map.get("busId");// 业务对象id
        // 2. 查询发布动态id是否存在
        Video video = mongoTemplate.findById(new ObjectId(busId), Video.class);
        if (video != null){
            // 3. 开始打分
            VideoScore videoScore = new VideoScore();
            videoScore.setUserId(Long.valueOf(userId));
            videoScore.setVideoId(video.getVid()); // 大数据系统pic
            videoScore.setDate(System.currentTimeMillis());
            videoScore.setScore(getScore(type,video));
            mongoTemplate.insert(videoScore);
        }
        log.debug("结束视频推荐打分业务listener监听");
    }

    /**
     * 打分业务方法
     * @param type 业务类型
     * @param video 动态对象
     * @return double
     */
    private double getScore(String type, Video video){
        Double score = 0d;
        switch (type) {
            case "0301":
                score=2d;
                break;
            case "0302":
                score=5d;
                break;
            case "0303":
                score = -5d;
                break;
            case "0304":
                score = 10d;
                break;
            default:
                break;
        }
        return score;
    }
}
